package com.ljfiction.book.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.liulishuo.magicprogresswidget.MagicProgressBar;
import com.ljfiction.book.Dialog.WxkefuDialog;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.DengjiActivity;
import com.ljfiction.book.activitys.HistoriesReadActivity;
import com.ljfiction.book.activitys.LoginActivity;

import com.ljfiction.book.activitys.MyPursActivity;
import com.ljfiction.book.activitys.MyfensiActivity;
import com.ljfiction.book.activitys.MymessageActivity;
import com.ljfiction.book.activitys.MyshupingActivity;
import com.ljfiction.book.activitys.RetrieveActivity;
import com.ljfiction.book.activitys.SetupActivity;
import com.ljfiction.book.activitys.TaskActivity;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserBean;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.EventTool;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringBean;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;


public class MineFragment extends BaseFragment {

    @BindView(R.id.userImage_main)
    CircularImageView userImageMain;
    @BindView(R.id.username2)
    TextView username2;
    @BindView(R.id.sex_main)
    ImageView sexMain;
    @BindView(R.id.guanzhu_main)
    TextView guanzhuMain;
    @BindView(R.id.fenshi_main)
    TextView fenshiMain;
    @BindView(R.id.mypurse)
    LinearLayout mypurse;
    @BindView(R.id.recharge)
    LinearLayout recharge;

    @BindView(R.id.history)
    LinearLayout history;
    Unbinder unbinder;
    @BindView(R.id.mainset)
    LinearLayout mainset;
    @BindView(R.id.isvipimage)
    ImageView isvipimage;
    @BindView(R.id.classmain)
    TextView classmain;
    @BindView(R.id.islogin)
    RelativeLayout islogin;
    @BindView(R.id.loginmian)
    TextView loginmian;
    @BindView(R.id.zhecemain)
    TextView zhecemain;
    @BindView(R.id.nologin)
    LinearLayout nologin;
    @BindView(R.id.signaturemain)
    TextView signaturemain;
    @BindView(R.id.progressBar3)
    MagicProgressBar progressBar3;



    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.imageView3)
    ImageView imageView3;
    @BindView(R.id.callkefu)
    LinearLayout callkefu;
    @BindView(R.id.dengjizhidu)
    LinearLayout dengjizhidu;

    private Context context;
    private Intent intent;
    private WxkefuDialog wxkefuDialog;
    private boolean isgetDataover=false;


    public static MineFragment newInstance() {
        MineFragment newFragment = new MineFragment();
        Bundle bundle = new Bundle();
        newFragment.setArguments(bundle);
        return newFragment;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        context = getActivity();
        intView();
        return view;
    }

    private void intView() {
        changview();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.userImage_main, R.id.username2, R.id.sex_main, R.id.guanzhu_main, R.id.fenshi_main, R.id.mypurse, R.id.recharge, R.id.history, R.id.mainset, R.id.loginmian, R.id.zhecemain, R.id.callkefu,R.id.dengjizhidu,R.id.main_task})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.userImage_main:
                if (UserManageBean.isLogin()) {
                    intent = new Intent(context, MymessageActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.username2:

                break;
            case R.id.sex_main:

                break;

            case R.id.guanzhu_main:
                if (!UserManageBean.isLogin(context)){
                    return;
                }
                intent = new Intent(context, MyfensiActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.fenshi_main:
                if (!UserManageBean.isLogin(context)){
                    return;
                }
                intent = new Intent(context, MyfensiActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.mypurse://我的钱包
                if (UserManageBean.isLogin()) {
                    EventTool.putEvent(context,"点击","点击","11_myWalletClick");
                    intent = new Intent(context, MyPursActivity.class);
                    startActivity(intent);
                } else {
                    Tool.showToast(StringBean.isLogin, context);
                }

                break;
            case R.id.recharge://我的书评/弹幕
                if (UserManageBean.isLogin()) {
                    intent = new Intent(context, MyshupingActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("userId", String.valueOf(UserManageBean.userBean.getUserId()));
                    startActivity(intent);
                } else {
                    Tool.showToast(StringBean.isLogin, context);
                }
                break;
            case R.id.history://历史纪录
                if (UserManageBean.isLogin()) {
                    intent = new Intent(context, HistoriesReadActivity.class);
                    startActivity(intent);
                } else {
                    Tool.showToast(StringBean.isLogin, context);
                }
                break;
            case R.id.mainset:
                intent = new Intent(context, SetupActivity.class);
                startActivity(intent);
                break;
            case R.id.loginmian:
                intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.zhecemain:
                intent= new Intent(context, RetrieveActivity.class);
                startActivityForResult(intent,10);
                break;
            case R.id.callkefu:
                if (wxkefuDialog == null) {
                    wxkefuDialog = new WxkefuDialog(context);
                }
                wxkefuDialog.show();
                break;
            case R.id.dengjizhidu:
                intent=new Intent(context, DengjiActivity.class);
                startActivity(intent);
                break;
            case R.id.main_task:
                if (UserManageBean.isLogin()) {
                    intent=new Intent(context, TaskActivity.class);
                    startActivity(intent);
                } else {
                    Tool.showToast(StringBean.isLogin, context);
                }
                break;
        }
    }

    @SuppressLint("SetTextI18n")
    private void changview() {
        if (UserManageBean.isLogin()&&UserManageBean.userBean != null && UserManageBean.userBean.getPseudonym() != null &&! "".equals(UserManageBean.userBean.getPseudonym())) {
            islogin.setVisibility(View.VISIBLE);
            nologin.setVisibility(View.GONE);
            sexMain.setVisibility(View.VISIBLE);
            isvipimage.setVisibility(View.VISIBLE);
            toGuanzhunum("0");
            toGuanzhunum("1");
            //tomessage();
            try {
                username2.setText(StringTool.isEmpty(UserManageBean.userBean.getPseudonym())?"书友":UserManageBean.userBean.getPseudonym());
                signaturemain.setText(UserManageBean.userBean.getUserAutograph().equals("")?"暂无签名":UserManageBean.userBean.getUserAutograph());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (UserManageBean.userBean.getUserSexInt() == 0) {
                sexMain.setImageResource(R.mipmap.sex_n);
            } else {
                sexMain.setImageResource(R.mipmap.sex_v);
            }
            if (UserManageBean.userBean.getVipGrade() > 0) {
                isvipimage.setVisibility(View.VISIBLE);
            } else {
                isvipimage.setVisibility(View.GONE);
            }
            classmain.setText("LV" + String.valueOf(UserManageBean.userBean.getUserGrade()));
            progressBar3.setPercent((float) (UserManageBean.userBean.getIntegration() - UserManageBean.userBean.getTopSource()) / (UserManageBean.userBean.getDownSource() - UserManageBean.userBean.getTopSource()));
            Glide.with(this).load(UserManageBean.userBean.getUserHeadPortraitURL()).into(userImageMain);
        } else {
            islogin.setVisibility(View.GONE);
            nologin.setVisibility(View.VISIBLE);
            sexMain.setVisibility(View.GONE);
            isvipimage.setVisibility(View.GONE);
            guanzhuMain.setText("关注");
            fenshiMain.setText("粉丝");
            signaturemain.setText("暂无签名");
            userImageMain.setImageResource(R.drawable.persenmoren);
            UserManageBean.setIsLogin(false);
        }


    }


    private void toGuanzhunum(final String type) {
        OkHttpUtils.get(HttpManager.IP + "/fans-followCount/" + UserManageBean.userBean.getUserId() + "/" + type)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        switch (type) {
                            case "1":
                                try {
                                    JSONObject jso = new JSONObject(s);
                                    if (jso.getInt("returnCode") == 200) {
                                        fenshiMain.setText("粉丝 " + String.valueOf(jso.getInt("data")));
                                    } else {
                                        fenshiMain.setText("粉丝");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case "0":
                                try {
                                    JSONObject js = new JSONObject(s);
                                    if (js.getInt("returnCode") == 200) {
                                        guanzhuMain.setText("关注 " + String.valueOf(js.getInt("data")));
                                    } else {
                                        guanzhuMain.setText("关注");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                break;
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!UserManageBean.isLogin()) {
            UserManageBean.setIsLogin(false);
            changview();
        } else {
            changview();
            if (!isgetDataover){
                dologin();
                isgetDataover=true;
            }

        }

    }

    private void dologin() {
        OkHttpUtils.post(HttpManager.IP + "/person-info")

                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        isgetDataover=false;
                        Gson gson = new Gson();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                UserBean user = gson.fromJson(jsonObject.getString("data"), UserBean.class);
                                UserManageBean.userBean = user;
                                UserManageBean.setIsLogin(true);
                                changview();
                            } else if ("400".equals(jsonObject.getString("returnCode"))){
                                UserManageBean.setIsLogin(false);
                                //messageDian.setVisibility(View.GONE);
                                changview();
                                showToast(jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

}
